//
//  ContactsViewController.m
//  Guazi
//
//  Created by koolearn on 11-5-5.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "GuaziAppDelegate.h"
#import "ContactsViewController.h"
#import "FriendGroup.h"
#import "ABContact.h"
#import "ABContactsHelper.h"
#import "User.h"
#import "ContactCell.h"
#import "ContactDetailViewController.h"
#import "GroupListEditViewController.h"
#import "GroupHeaderView.h"
#import "ColorUtils.h"


@interface ContactsViewController(private)
- (NSMutableArray*) readPhoneContacts;
- (BOOL) isRegistered;

- (NSMutableArray*) loadFrequentContacts;
- (NSArray*) loadGroup;
- (void) loadContactForSection:(NSInteger)section;
- (void) loadContactForGroup:(FriendGroup*)group continueNextGroup:(BOOL)b force:(BOOL)force;
- (void) didLoadContactForGroup:(id)sender obj:(NSObject*)obj;

- (NSArray*) restoreLocalContacts;
- (NSMutableArray*) getNewContacts:(NSArray*)phoneContacts localContacts:(NSArray*)localContacts;
- (CGFloat) getCellHeight:(NSIndexPath*)indexPath;

- (void) uploadNewContacts:(NSArray*)newContacts;
@end



@implementation ContactsViewController


@synthesize groups;


#pragma mark -
#pragma mark Initialization

/*
- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    if ((self = [super initWithStyle:style])) {
    }
    return self;
}
*/


#pragma mark -
#pragma mark View lifecycle


- (void)viewDidLoad 
{
    [super viewDidLoad];
	
	self.navigationItem.title = @"通讯录";
	self.navigationController.navigationBar.tintColor = [UIColor navigationColorForTab:0];
	
	self.groups = [NSMutableArray array];
    //[self resetData];
}


- (void) resetData
{
    [self.groups removeAllObjects];
    
	NSMutableArray* phoneContacts = [self readPhoneContacts];
	NSInteger groupIndex = 0;
	FriendGroup* firstGroup = nil;
	
	if ( [self isRegistered] ) {
		NSMutableArray* topFrequent = [self loadFrequentContacts];
		//if ( topFrequent != nil && [topFrequent count] > 0 ) {
        FriendGroup* frequentGroup = [FriendGroup groupWithId:-1 name:@"常用联系人"];
        frequentGroup.loaded = YES;
        frequentGroup.expanded = YES;
        frequentGroup.friends = topFrequent;
        frequentGroup.index = groupIndex++;
        [groups addObject:frequentGroup];
		//}
		
		FriendGroup* unGroup = nil;
		NSArray* mygroups = [self loadGroup];
        if ( mygroups != nil && [mygroups count] > 0 ) {
			for ( FriendGroup* group in mygroups ) {
				group.index = groupIndex++;
				[groups addObject:group];
				//[group restoreUsers];
                
                //group.friends = [TwitterClient getUserInGroupSync:group.groupId];
                
				if ( firstGroup == nil ) firstGroup = group;
				if ( group.groupId == 0 ) unGroup = group;
			}
		}
		
		
		NSMutableArray* friends = [[NSMutableArray alloc] init];
		//if ( unGroup && unGroup.friendCount > 0 ) {
		//	NSMutableArray* ungroupedFriends = [TwitterClient getUserInGroupSync:0];
		//	unGroup.loaded = YES;
		//	[friends addObjectsFromArray:ungroupedFriends];
		//}
        
		NSArray* localContacts = [self restoreLocalContacts];
		NSMutableArray* newContacts = [self getNewContacts:phoneContacts localContacts:localContacts];
		if ( newContacts != nil && [newContacts count] > 0 ) {
			[friends addObjectsFromArray:newContacts];
		}
        
		if ( !unGroup && [friends count] > 0 ) {
			unGroup = [[FriendGroup alloc] init];
			unGroup.groupId = 0;
			unGroup.name = @"未分组";
			unGroup.loaded = YES;
			[groups addObject:unGroup];
			[unGroup release];
		}
		
		for ( User* u in friends ) {
			[unGroup.friends addObject:u ];
		}
        
        [friends release];
		
		//[self uploadNewContacts:newContacts];
		
	}
	else {
		FriendGroup* group = [FriendGroup groupWithId:0 name:@"本地通讯录"];
		group.loaded = YES;
		group.restored = YES;
		group.friends = phoneContacts;
		group.index = groupIndex++;
		[groups addObject:group];
	}
	
	//从网络加载数据
	if ( firstGroup != nil ) {
		[self loadContactForGroup:firstGroup continueNextGroup:YES force:NO];
	}
    
	if ( [groups count] > 0 ) {
		[self sectionDidSelected:0];
	}
}



 - (void)viewWillAppear:(BOOL)animated 
{
    [self resetData];
	[self.tableView reloadData];
	[super viewWillAppear:animated];
 }




/*
 - (void)viewDidAppear:(BOOL)animated {
 [super viewDidAppear:animated];
 }
 */

/*
 - (void)viewWillDisappear:(BOOL)animated {
 [super viewWillDisappear:animated];
 }
 */
/*
 - (void)viewDidDisappear:(BOOL)animated {
 [super viewDidDisappear:animated];
 }
 */
/*
 // Override to allow orientations other than the default portrait orientation.
 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
 // Return YES for supported orientations
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
 }
 */


#pragma mark -
#pragma mark 选中分组的操作

//选中某个分组
- (void) sectionDidSelected:(NSInteger)section
{
	FriendGroup* group = [groups objectAtIndex:section];
	if ( group.expanded ) return;
	
	for ( int i=0; i<[groups count]; i++ ) {
		FriendGroup* g = [groups objectAtIndex:i];
		if ( g.expanded ) {
			[self collapseSecton:i];
		}
	}
	
	if ( !group.loaded ) {
		[self loadContactForSection:section];
	}
	
	[self expandSection:section];
	//[self.tableView reloadData];
}


- (void) expandSection:(NSInteger)section
{
	FriendGroup* group = [groups objectAtIndex:section];
	if ( group.expanded ) return;
	
	NSArray* users = group.friends;
	NSMutableArray* insertRows = [NSMutableArray arrayWithCapacity:[users count]];
	
	[self.tableView beginUpdates];
	for ( int i=0; i<[users count]; i++ ) {
		NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:section];
		[insertRows addObject:indexPath];
	}
	
	group.expanded = YES;
	[self.tableView insertRowsAtIndexPaths:insertRows withRowAnimation:UITableViewRowAnimationNone];
	[self.tableView endUpdates];
}


- (void) collapseSecton:(NSInteger)section
{
	FriendGroup* group = [groups objectAtIndex:section];
	if ( !group.expanded ) return;
	
	NSArray* users = group.friends;
	NSMutableArray* deleteRows = [NSMutableArray arrayWithCapacity:[users count]];
	
	[self.tableView beginUpdates];
	for ( int i=0; i<[users count]; i++ ) {
		NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:section];
		[deleteRows addObject:indexPath];
	}
	
	group.expanded = NO;
	[self.tableView deleteRowsAtIndexPaths:deleteRows withRowAnimation:UITableViewRowAnimationMiddle];
	[self.tableView endUpdates];
	
	[self.tableView reloadSections:[NSIndexSet indexSetWithIndex:section] withRowAnimation:UITableViewRowAnimationNone];
}




#pragma mark -
#pragma mark 从服务器中加载数据

//从服务器上得到所有组信息
- (NSArray*) loadGroup
{
	NSArray* groupList = [TwitterClient getGroups];
	
	for ( FriendGroup* group in groupList ) {
		if ( group.groupId > 0 ) [group updateDB];
	}
	
	return groupList;
}


//得到常用联系人信息
- (NSArray*) loadFrequentContacts
{
	GuaziAppDelegate* appDelegate = [GuaziAppDelegate getAppDelegate];
	NSArray* friends = [TwitterClient getFriendsSync:appDelegate.user.userId page:0 rowsPerPage:20];
	return friends;
}


//异步加载section下的联系人
- (void) loadContactForSection:(NSInteger)section
{
	FriendGroup* group = [groups objectAtIndex:section];
	[self loadContactForGroup:group continueNextGroup:NO force:NO];
}


//异步加载分组下的联系人
- (void) loadContactForGroup:(FriendGroup*)group continueNextGroup:(BOOL)b force:(BOOL)force
{
	if ( !force && group.loaded ) return;
	if ( client ) return;
	
	SEL action = nil;
	if ( b ) {
		action = @selector(didLoadContactForGroupContinue:obj:);
	}
	else {
		action = @selector(didLoadContactForGroup:obj:);
	}
	
	client = [[TwitterClient alloc] initWithTarget:self action:action];
	client.context = group;
	[client getUsersInGroup:group.groupId];
}


//异步加载分组下的联系人。本分组加载完成后，在加载下一个分组的联系人
- (void) didLoadContactForGroupContinue:(id)sender obj:(NSObject *)obj
{
	client = nil;
	TwitterClient* twitterClient = (TwitterClient*) sender;
	FriendGroup* group = (FriendGroup*) twitterClient.context;
	
	[self didLoadContactForGroup:sender obj:obj];
	
	int index = -1;
	for ( int i=0; i<[groups count]; i++ ) {
		FriendGroup* g = [groups objectAtIndex:i];
		if ( g.groupId == group.groupId ) {
			index = i;
			break;
		}
	}
	
	if ( index < [groups count] - 1 ) {
		index++;
		group = [groups objectAtIndex:index];
		//if ( group.groupId > 0 ) {
			[self loadContactForGroup:group continueNextGroup:YES force:NO];
		//}
	}
	
	
}


//异步加载分组下的联系人
- (void) didLoadContactForGroup:(id)sender obj:(NSObject*)obj
{
	client = nil;
	TwitterClient* twitterClient = (TwitterClient*) sender;
	FriendGroup* group = (FriendGroup*) twitterClient.context;
	
	NSMutableArray* users = [NSMutableArray array];
	
	if ( twitterClient.hasError ) {
		[twitterClient alert];
		//如果没有从网络读到，则从本地加载
		[group restoreUsers];
		return;
	}
	else {
		if ( obj == nil ) return;
		if ( ![obj isKindOfClass:[NSDictionary class]] ) return;
		
		NSDictionary* dic = (NSDictionary*) obj;
		NSArray* arr = [dic objectForKey:@"friends"];
		
		if ( arr != nil && (id)arr != [NSNull null] && [arr count] > 0 ) {
			for ( int i=0; i<[arr count]; i++ ) {
				NSDictionary* userDic = [arr objectAtIndex:i];
				if ( userDic == nil || ![userDic isKindOfClass:[NSDictionary class]] ) continue;
				User* user = [[User alloc] initWithJsonDictionary:userDic];
				[users addObject:user];
				[user updateDB:YES withName:NO withAccount:NO];
				[user release];
				
				NSDictionary* tweetDic = [userDic objectForKey:@"lastest_weibo"];
				if ( tweetDic != nil && (id)tweetDic!=[NSNull null] && [userDic isKindOfClass:[NSDictionary class]]) {
					Status* status = [Status statusWithJsonDictionary:tweetDic type:TWEET_TYPE_FRIENDS];
					user.status = status;
				}
			}
		}
	}
	
	//更新group下的人员
	group.friends = users;
	group.loaded = YES;
	if ( group.expanded ) {
		[self.tableView reloadData];
	}
	
	//更新数据库
	[FriendGroup setUsers:users groupId:group.groupId];
}


#pragma mark -
#pragma mark 本地通讯录操作及上传数据

//读本地通讯录
- (NSMutableArray*) readPhoneContacts 
{
	NSArray* contacts = [ABContactsHelper contacts];
	NSMutableArray* users = [NSMutableArray arrayWithCapacity:[contacts count]];
	
	User* user = nil;
	for ( ABContact* contact in contacts ) {
		user = [[User alloc] initWithABContact:contact];
		[users addObject:user];
		[user release];
	}
	return users;
}


//得到本地保存的通讯录信息
- (NSArray*) restoreLocalContacts
{
	return [User loadAllUsers];
}


//比较本地通讯录与服务器下载的通讯录，得到通讯录新建人员。这些人员需要上传到服务器
- (NSArray*) getNewContacts:(NSArray*)phoneContacts localContacts:(NSArray*)localContacts
{
	NSMutableDictionary* phones = [[NSMutableDictionary alloc] initWithCapacity:[localContacts count]];
	//NSMutableDictionary* names = [[NSMutableDictionary alloc] initWithCapacity:[localContacts count]];
	NSMutableArray* newContacts = [NSMutableArray array];
	
	for ( User* u in localContacts ) {
		[phones setObject:@"" forKey:u.phone];
		//[names setObject:@"" forKey:u.name];
	}
	
	for ( User* u in phoneContacts ) {
		if ( [phones objectForKey:u.phone] == nil ) {
			[newContacts addObject:u];
		}
	}
	
	[phones release];
	//[names release];
	
	return newContacts;
}


//上传本地通讯录
- (void) uploadNewContacts:(NSArray*)newContacts
{
	if ( client ) return;
	client = [[TwitterClient alloc] initWithTarget:self action:@selector(didUploadNewContacts:obj:)];
	[client dataupContacts:newContacts];
}


- (void) didUploadNewContacts:(TwitterClient*)aClient obj:(id)obj
{
	client = nil;
}


//判断是否注册了
- (BOOL) isRegistered
{
	User* user = [GuaziAppDelegate getAppDelegate].user;
	if ( user != nil ) return YES;
	return NO;
}




#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{
	return [groups count];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{
	FriendGroup* group = [groups objectAtIndex:section];
	if ( !group.expanded ) {
		return 0;
	}
	else {
		NSArray*  users= group.friends;
		if ( users == nil ) return 0;
		else return [users count];
	}
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"ContactsViewCell";
    
    ContactCell *cell = (ContactCell*) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[ContactCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    
	FriendGroup* group = [groups objectAtIndex:indexPath.section];
	User* user = [group.friends objectAtIndex:indexPath.row];
 	
	CGRect frame = CGRectMake(LEFT, 1, CELL_WIDTH, [self getCellHeight:indexPath] - 2 );
	[cell update:user frame:frame];
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
	return 30;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
	FriendGroup* group = [groups objectAtIndex:section];

	CGRect frame = CGRectMake(0, 0, 320, 30);
	GroupHeaderView* headerView = [[[GroupHeaderView alloc] initWithFrame:frame group:group section:section] autorelease];
	
	return (UIView*) headerView;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	return (CGFloat) [self getCellHeight:indexPath];
}


- (CGFloat) getCellHeight:(NSIndexPath*)indexPath
{
	FriendGroup* group = [groups objectAtIndex:indexPath.section];
	User* user = [group.friends objectAtIndex:indexPath.row];
	
	CGFloat height = 20;
	if ( user.phone != nil && [user.phone length] > 0 ) {
		height += 20;
	}
	
	Status* status = user.status;
	if ( status != nil ) {
		height += status.textBounds.size.height + 20;
	}
	
	if ( height < 54 ) height = 54;
	return height;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/


/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/


/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/


/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/


#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	FriendGroup* group = [groups objectAtIndex:indexPath.section];
	User* user = [group.friends objectAtIndex:indexPath.row];

	ContactDetailViewController* profile = [[ContactDetailViewController alloc] initWithUser:user];
	profile.hidesBottomBarWhenPushed = YES;
	[self.navigationController pushViewController:profile animated:true];
    [profile release];
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Relinquish ownership any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	self.groups = nil;
	if (client) {
		[client cancel];
		[client release];
	}
}


- (void)dealloc {
	[groups release];
	if (client) {
		[client cancel];
		[client release];
	}
    [super dealloc];
}


@end

